package xyz.thoughtset.viewer.executor.blocks.tool;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.tool.definition.DefaultToolDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import xyz.thoughtset.viewer.executor.blocks.executor.BlockExecutorManager;
import xyz.thoughtset.viewer.executor.blocks.tool.json.ParamJsonSchemaGenerator;
import xyz.thoughtset.viewer.modules.fun.dao.FunInfoDao;
import xyz.thoughtset.viewer.modules.fun.service.FunInfoService;
import xyz.thoughtset.viewer.modules.step.entity.block.BlockBodyEle;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class FunctionCallBlockToolCallbackProvider {

    @Autowired
    private FunInfoDao funInfoDao;
    @Autowired
    private BlockExecutorManager blockExecutorManager;
    @Autowired
    private ObjectMapper objectMapper;


    public ToolCallback[] getToolCallbacks(String blockId, Map<String, BlockBodyEle> funParamMap) {

        ToolCallback[] toolCallbacks = this.funInfoDao.findBlockFunsWithInParam(blockId).stream()
                .map((funInfo) -> {
                    String funTitle = funInfo.getTitle();
                    String funRemark = funInfo.getRemark();
                    BlockBodyEle bodyEle = funParamMap.get(funInfo.getId());
                    String remark = bodyEle.getRemark();
                    remark = StringUtils.hasText(remark) ? remark : funRemark;
                    DefaultToolDefinition toolDefinition = (DefaultToolDefinition) DefaultToolDefinition.builder()
                            .name(funTitle)
                            .description(StringUtils.hasText(remark) ? remark : funTitle)
                            .inputSchema(ParamJsonSchemaGenerator.generateForFunInput(funInfo))
                            .build();
                    String funId = funInfo.getId();
                    return new FunctionCallBlockToolCallback(toolDefinition,funParamMap.get(funId),blockExecutorManager,objectMapper,funId);
                })
                .toArray(ToolCallback[]::new);
        return toolCallbacks;
    }

}
